<?php

namespace app\middleware;

use app\manager\RedisInstance;
use app\model\RegisterModel;
use app\model\UserModel;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use think\facade\Request;
use think\facade\Session;
use think\response\Json;



/**todo
 * 统一返回格式分装
 * 新增拦截器完成统一异常捕获
 * */
class CheckToken
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $cookie = $_COOKIE;
        //print_r($cookie);exit();
        $urls = [
            '/login/login',
            'register'
        ];
        //echo Request::url();exit();
        if (in_array(Request::url(),$urls)){
            return $next($request);
        } else {
            if (empty($cookie['token'])) {
                throw new Exception('未登录1');
            }

            $ris = RedisInstance::get($cookie['token']);
            if (!empty($ris)){
                $user = UserModel::seletUserById($ris);
                session_start();
                $_SESSION['uid']=$user;
                return $next($request);
            } else {
                throw new Exception('未登录');
            }
        }
    }
}
